/* eslint no-unused-vars:0 */
import React from 'react';
import './index.less';
import {
    Form,
    Card,
    Input,
    Button,
    Select,
    Col,
    Upload,
    Icon,
    message
} from 'antd';
import AlterPassword from './alterPassword';

const Option = Select.Option;

let token = '';
// 初始头像
let initialUrl = 'http://pq1u28g7w.bkt.clouddn.com/initial-avatar';
class PersonalCenter extends React.Component {
    state = {
        userInfo: {
            username: '',
            sex: '',
            contact: '',
            college: '',
            mail: '',
            imageUrl: ''
        },
        loading: false,
        alter_visible: false
    };

    componentDidMount() {
        this.getInfo();
    }

    // 更新头像url
    updateImageUrl = (imageUrl) => {
        this.$post('user/updateImageUrl', { imageUrl: imageUrl })
            .then((res) => {
                if (res.event === 0) {
                    message.success('上传成功');
                }
            })
            .catch((error) => {
                console.log(error);
            });
    };

    // 上传前检查
    beforeUpload = (file) => {
        const isJPG = file.type === 'image/jpeg';
        const isPNG = file.type === 'image/png';
        if (!isJPG && !isPNG) {
            message.error('不支持该格式的图片!');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            message.error('头像大小不得大于2MB!');
        }
        return (isJPG || isPNG) && isLt2M;
    };

    // 从后台获取生成的token
    getUploadToken = () => {
        this.$post('user/getUploadToken')
            .then((res) => {
                this.setState({ token: res });
                token = res;
                // return res;
            })
            .catch((error) => {
                console.log(error);
            });
    };

    // 头像修改
    handleChange = (info) => {
        if (info.file.status === 'uploading') {
            this.setState({ loading: true });
            return;
        }
        if (info.file.status === 'done') {
            // Get this url from response in real world.
            let key = info.file.response.key;
            if (!key) {
                message.error('上传失败！请刷新或联系管理员');
            }
            let imageUrl =
                'http://pq1u28g7w.bkt.clouddn.com/' + key + '-avatar';
            this.setState({
                imageUrl: imageUrl
            });
            this.updateImageUrl(imageUrl);
        }
    };

    //获取用户个人信息
    getInfo = () => {
        this.$post('/user/findById')
            .then((res) => {
                this.setState({ userInfo: res });
                if (res.imageUrl) {
                    this.setState({ imageUrl: res.imageUrl });
                } else {
                    this.setState({ imageUrl: initialUrl });
                }
            })
            .catch((error) => {
                console.log(error);
            });
    };

    // 开启修改密码弹窗
    showAlterModal = () => {
        this.setState({
            alter_visible: true
        });
    };

    // 关闭修改密码弹窗
    close = () => {
        this.setState({
            alter_visible: false
        });
    };

    // 修改个人资料
    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, values) => {
            this.$post('user/update', values)
                .then((res) => {
                    if (res.msg === 'success') console.log(res.msg);
                    message.success('修改成功');
                })
                .catch((err) => {
                    console.log(err);
                });
        });
    };

    render() {
        const { getFieldDecorator } = this.props.form;

        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 8 }
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 16 }
            }
        };

        const tailFormItemLayout = {
            wrapperCol: {
                xs: {
                    span: 24,
                    offset: 0
                },
                sm: {
                    span: 16,
                    offset: 8
                }
            }
        };

        if (!this.state.token) this.getUploadToken();

        // if (!this.state.imageUrl) this.getInfo();

        const imageUrl = this.state.imageUrl;

        return (
            <div className="body">
                <div style={{ marginTop: '20px' }}>
                    <span style={{ fontSize: '26px' }}>个人中心</span>
                </div>
                <Card title="编辑个人信息">
                    <Col span="10">
                        <div id="update">
                            <Form
                                {...formItemLayout}
                                onSubmit={this.handleSubmit}>
                                <Form.Item label="用户名：">
                                    <Input
                                        prefix={
                                            <Icon
                                                type="user"
                                                style={{
                                                    color: 'rgba(0,0,0,.25)'
                                                }}
                                            />
                                        }
                                        value={this.state.userInfo.username}
                                        disabled
                                    />
                                </Form.Item>
                                <Form.Item label="性别：">
                                    {getFieldDecorator('sex', {
                                        initialValue:
                                            this.state.userInfo.sex === '男'
                                                ? '1'
                                                : '0'
                                    })(
                                        <Select style={{ width: 100 }}>
                                            <Option value="0">女</Option>
                                            <Option value="1">男</Option>
                                        </Select>
                                    )}
                                </Form.Item>
                                <Form.Item label="学校：">
                                    <Input
                                        prefix={
                                            <Icon
                                                type="home"
                                                style={{
                                                    color: 'rgba(0,0,0,.25)'
                                                }}
                                            />
                                        }
                                        value={this.state.userInfo.college}
                                        disabled
                                    />
                                </Form.Item>
                                <Form.Item label="联系方式：">
                                    {getFieldDecorator(
                                        'contact',
                                        {
                                            initialValue: this.state.userInfo
                                                .contact
                                        },
                                        {
                                            rules: [
                                                {
                                                    message:
                                                        '请输入正确的联系方式！'
                                                }
                                            ]
                                        }
                                    )(
                                        <Input
                                            prefix={
                                                <Icon
                                                    type="phone"
                                                    style={{
                                                        color: 'rgba(0,0,0,.25)'
                                                    }}
                                                />
                                            }
                                        />
                                    )}
                                </Form.Item>
                                <Form.Item label="E-mail：">
                                    {getFieldDecorator(
                                        'mail',
                                        {
                                            initialValue: this.state.userInfo
                                                .mail
                                        },
                                        {
                                            rules: [
                                                {
                                                    type: 'email',
                                                    message:
                                                        '请输入正确的邮箱地址！'
                                                }
                                            ]
                                        }
                                    )(
                                        <Input
                                            prefix={
                                                <Icon
                                                    type="mail"
                                                    style={{
                                                        color: 'rgba(0,0,0,.25)'
                                                    }}
                                                />
                                            }
                                        />
                                    )}
                                </Form.Item>
                                <Form.Item {...tailFormItemLayout}>
                                    <Button onClick={this.showAlterModal}>
                                        修改密码
                                    </Button>
                                    <Button type="primary" htmlType="submit">
                                        确定
                                    </Button>
                                </Form.Item>
                            </Form>
                        </div>
                    </Col>
                    <Col span="14">
                        {this.state.token ? (
                            <Upload
                                name="file"
                                listType="picture-card"
                                className="avatar-uploader"
                                showUploadList={false}
                                action="http://upload-z2.qiniup.com"
                                data={{
                                    token: this.state.token
                                }}
                                multiple={false}
                                beforeUpload={this.beforeUpload}
                                onChange={this.handleChange}>
                                {imageUrl ? (
                                    <img src={imageUrl} alt="avatar" />
                                ) : (
                                    <img src={initialUrl} alt="avatar" />
                                )}
                            </Upload>
                        ) : (
                            <img src={initialUrl} alt="avatar" />
                        )}
                    </Col>
                </Card>
                <AlterPassword
                    alter_visible={this.state.alter_visible}
                    close={this.close}
                />
            </div>
        );
    }
}
export default Form.create()(PersonalCenter);
